package com.ruoyi.common.utils.map;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Component
public class BaiduMapUtil {

    private static final String apiKey = "bzAREW4WWaUGB35wuMLCWKq3lXzukwqM";
    private static final String geocodeUrl = "http://api.map.baidu.com/geocoding/v3/";
    private static final RestTemplate restTemplate = new RestTemplate();
    private static final ObjectMapper objectMapper = new ObjectMapper();


    public Location getLocationByAddress(String address){

        Location location = new Location();
        try {
            // 手动编码地址参数
            String encodedAddress = URLEncoder.encode(address, StandardCharsets.UTF_8.toString());

            // 构建完整的URL并创建URI对象
            String urlString = String.format("%s?address=%s&output=json&ak=%s",
                    geocodeUrl,
                    encodedAddress,
                    apiKey);
            URI uri = new URI(urlString);
            // 打印构建的URL以便调试
            System.out.println("Request URL: " + uri);
            // 使用URI对象发送GET请求
            String response = restTemplate.getForObject(uri, String.class);
            System.out.println("API Response: " + response);
            // 解析JSON响应
            JsonNode rootNode = objectMapper.readTree(response);
            int status = rootNode.path("status").asInt();
            if (status == 0) {
                JsonNode locationNode = rootNode.path("result").path("location");
                double lng = locationNode.path("lng").asDouble();
                double lat = locationNode.path("lat").asDouble();
                System.out.println("经度: " + lng + ", 纬度: " + lat);
                location.setLongitude(lng);
                location.setLatitude(lat);
            } else {
                String message = rootNode.path("msg").asText("");
                System.out.println("请求失败: " + message);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("An error occurred while processing the request", e);
        }

        return location;
    }


}

